package gconsts

import (
	"context"
	"os"

	email "gitee.com/abril-cx/gtools/gemail"
	log "gitee.com/abril-cx/gtools/glog"
	middleware "gitee.com/abril-cx/gtools/gmiddleware"
	mongo "gitee.com/abril-cx/gtools/gmongo"
	redis "gitee.com/abril-cx/gtools/gredis"
	utils "gitee.com/abril-cx/gtools/gutils"
	"github.com/gin-gonic/gin"
)

var (
	APP_NAME_RELATED    = ""
	APP_SERVICE_RELATED = map[string]Service{}
	APP_ARGS            = map[string]string{}
	COLONY              = ""
	APP_CLOUD           = false
	APP_CORS            = false
	APP_DROP            = false
	APP_DEBUG           = false

	STATIC_PATH = ""

	APP_APPID  = ""
	APP_SECRET = ""

	APP_REDIS_HOST = "127.0.0.1"
	APP_REDIS_PORT = "6379"

	APP_MONGODB_HOST = "127.0.0.1"
	APP_MONGODB_PORT = "27017"

	APP_EMAIL_HOST     = "smtp.126.com"
	APP_EMAIL_PORT     = 25
	APP_EMAIL_NICKNAME = ""
	APP_EMAIL_USER     = "XXXXXXXXXXXX"
	APP_EMAIL_PASSWORD = "XXXXXXXXXXXX"
)

func Load() {
	formatArgs()
	loadEnv()
	loadArgs()
	log.IS_DEBUG = APP_DEBUG
	middleware.CorsStatus = APP_CORS
	if !APP_DEBUG {
		gin.SetMode(gin.ReleaseMode)
	}
	if APP_CLOUD {
		APP_REDIS_HOST = COLONY + "-redis-1"
		APP_MONGODB_HOST = COLONY + "-mongo-1"
	}
}

func Init(app_name string, services map[string]Service) error {
	log.Primary("服务名称: ", app_name)
	log.Primary("生产环境: ", APP_CLOUD)
	log.Primary("跨域: ", APP_CORS)
	log.Primary("debug: ", APP_DEBUG)
	APP_NAME_RELATED = app_name
	mongo.SERVICE = app_name
	APP_SERVICE_RELATED = services
	initRedis(app_name)
	app_name_db := app_name[:len(app_name)-2] + "db"
	err := initMongodb(app_name_db)
	if err != nil {
		return err
	}
	initEmail()
	return nil
}

func loadArgs() {
	cloud, ok := APP_ARGS["-c"]
	if ok {
		if cloud == "t" {
			APP_CLOUD = true
		} else {
			APP_CLOUD = false
		}
	}
	debug, ok := APP_ARGS["-d"]
	if ok {
		if debug == "t" {
			APP_DEBUG = true
		} else {
			APP_DEBUG = false
		}
	}
	cors, ok := APP_ARGS["-o"]
	if ok {
		if cors == "t" {
			APP_CORS = true
		} else {
			APP_CORS = false
		}
	} else {
		if !APP_CLOUD {
			APP_CORS = true
		}
	}
	_, ok = APP_ARGS["--drop"]
	if ok {
		APP_DROP = true
	}
}

func formatArgs() {
	args := os.Args
	key := ""
	for i := 1; i < len(args); i++ {
		value := args[i]
		if value[0] == '-' {
			key = ""
			if value[1] == '-' {
				APP_ARGS[value] = ""
			} else {
				key = value
			}
		} else {
			if key != "" {
				APP_ARGS[key] = value
			}
		}
	}
}

func loadEnv() {
	COLONY = loadEnvString("COLONY", "colony")

	APP_CLOUD = loadEnvBool("APP_CLOUD", APP_CLOUD)
	APP_CORS = loadEnvBool("APP_CORS", APP_CORS)
	APP_DROP = loadEnvBool("APP_DROP", APP_DROP)
	APP_DEBUG = loadEnvBool("APP_DEBUG", APP_DEBUG)

	APP_APPID = loadEnvString("APP_APPID", APP_APPID)
	APP_SECRET = loadEnvString("APP_SECRET", APP_SECRET)

	APP_REDIS_HOST = loadEnvString("APP_REDIS_HOST", APP_REDIS_HOST)
	APP_REDIS_PORT = loadEnvString("APP_REDIS_PORT", APP_REDIS_PORT)

	APP_MONGODB_HOST = loadEnvString("APP_MONGODB_HOST", APP_MONGODB_HOST)
	APP_MONGODB_PORT = loadEnvString("APP_MONGODB_PORT", APP_MONGODB_PORT)

	APP_EMAIL_HOST = loadEnvString("APP_EMAIL_HOST", APP_EMAIL_HOST)
	APP_EMAIL_PORT = loadEnvInt("APP_EMAIL_PORT", APP_EMAIL_PORT)
	APP_EMAIL_NICKNAME = loadEnvString("APP_EMAIL_NICKNAME", APP_EMAIL_NICKNAME)
	APP_EMAIL_USER = loadEnvString("APP_EMAIL_USER", APP_EMAIL_USER)
	APP_EMAIL_PASSWORD = loadEnvString("APP_EMAIL_PASSWORD", APP_EMAIL_PASSWORD)
}

func loadEnvString(key string, app_data string) string {
	env_data := os.Getenv(key)
	if env_data != "" {
		return env_data
	}
	return app_data
}

func loadEnvBool(key string, app_data bool) bool {
	env_data := os.Getenv(key)
	if env_data != "" {
		if env_data == "true" {
			return true
		} else {
			return false
		}
	}
	return app_data
}

func loadEnvInt(key string, app_data int) int {
	env_data := os.Getenv(key)
	if env_data != "" {
		value, err := utils.StrToInt64(env_data)
		if err == nil {
			return int(value)
		}
	}
	return app_data
}

func initRedis(app_name string) {
	redis.Prefix = app_name
	redis.Host = APP_REDIS_HOST
	redis.Port = APP_REDIS_PORT
	redis.Init()
}

func initMongodb(app_name string) error {
	mongo.Host = APP_MONGODB_HOST
	mongo.Port = APP_MONGODB_PORT
	err := mongo.Init(app_name)
	if err != nil {
		return err
	}
	if APP_DROP {
		if APP_CLOUD {
			drops, ok := APP_ARGS["-drop"]
			if ok {
				if drops == "t" {
					mongo.MongoConn.Drop(context.Background())
				}
			}
		} else {
			mongo.MongoConn.Drop(context.Background())
		}
	}
	return nil
}

func initEmail() {
	email.EMAIL_NICKNAME = APP_EMAIL_NICKNAME
	email.EMAIL_USER = APP_EMAIL_USER
	email.EMAIL_PASSWORD = APP_EMAIL_PASSWORD
}

func GetGrpcHostPort(service string, local_port string) string {
	if APP_CLOUD {
		return COLONY + "-" + service + "-1:4242"
	} else {
		return "127.0.0.1:" + local_port
	}
}
